package cn.bocweb.spinning.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.GetCtypeBean;
import cn.bocweb.spinning.model.Bean.GetFlagBean;
import cn.bocweb.spinning.model.Bean.GetIhomeBean;
import cn.bocweb.spinning.model.Bean.ItemBean;
import cn.bocweb.spinning.model.Bean.OldFangBannerBean;
import cn.bocweb.spinning.model.Bean.OldFangBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.activity.InfoDetailActivity;
import cn.bocweb.spinning.view.activity.InfoSearchActivity;
import cn.bocweb.spinning.view.activity.LoginAcivity;
import cn.bocweb.spinning.view.activity.MyCommentActivity;
import cn.bocweb.spinning.view.adapter.BannerAdapter;
import cn.bocweb.spinning.view.adapter.InfoItemAdapter;
import cn.bocweb.spinning.view.adapter.MainBannerAdapter;
import cn.bocweb.spinning.view.adapter.ProfessionInfoAdapter;
import cn.bocweb.spinning.view.common.BaseView;
import cn.bocweb.spinning.view.common.SwipeRefreshHelper;
import cn.bocweb.spinning.view.dialog.ItemDialog;
import cn.bocweb.spinning.view.dialog.LoadingDialog;
import de.greenrobot.event.EventBus;

/**
 * Created by chenchangxing on 15/12/25.
 */
public class InfoFragment extends Fragment implements BaseView, View.OnClickListener {
    @Bind(R.id.recycleview)
    RecyclerView recycleview;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.info_btn_msg)
    ImageView infoBtnMsg;

    boolean hasShown;
    boolean isOldFang;
    LinearLayout dot;
    ItemDialog itemDialog;
    List<ItemBean> itemBeanList;

    @Bind(R.id.info_list)
    ListView infoList;

    List<ImageView> imageViews, dotList;
    MainBannerAdapter mainBannerAdapter;
    LinearLayout.LayoutParams layout;
    Timer timer;
    ProfessionInfoAdapter infoAdapter;
    List<GetIhomeBean.DataEntity> itemsList;
    InfoItemAdapter infoItemAdapter;
    ImageView dots;
    LinearLayout.LayoutParams selectParams;
    LinearLayout.LayoutParams unselect;
    List<GetCtypeBean.DataEntity> infoItem;
    UserPresenter presenter;
    LoadingDialog dialog;
    String userid;
    SwipeRefreshHelper helper;
    int ctype = 0;
    List<String> ctypeIdList;
    List<String> bannerIdList;


    List<String> bannerTitle, bannerUri;
    int page = 1, typeid, currentPosition;
    boolean isListLoading = false, isLastPage = false, isLoad = false;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int i = msg.arg1;
            initSelectDot(i);
        }
    };

    String infoType;
    TextView infoBannerTitle;
    ConvenientBanner infoBanner;
    @Bind(R.id.info_refresh)
    SwipeRefreshLayout infoRefresh;
    @Bind(R.id.info_content)
    LinearLayout infoContent;
    @Bind(R.id.imageview_dialog)
    ImageView imageviewDialog;

    private void initSelectDot(int select) {
        if (dotList.size() != 0) {
            for (int i = 0; i < dotList.size(); i++) {
                ImageView img = dotList.get(i);
                if (i == select) {
                    img.setLayoutParams(selectParams);
                    img.setImageResource(R.drawable.bg_dots_select);
                } else {
                    img.setLayoutParams(unselect);
                    img.setImageResource(R.drawable.bg_dots);
                }
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_info, container, false);
        ButterKnife.bind(this, view);


        bannerIdList = new ArrayList<>();
        bannerUri = new ArrayList<>();
        itemBeanList = new ArrayList<>();
        itemDialog = new ItemDialog(getContext(), itemBeanList);
        itemDialog.setOnConfirmListener(new ItemDialog.OnConfirmListener() {
            @Override
            public void onClick(int confirm, String id) {
                if (!infoRefresh.isRefreshing()) {
                    if (ctype != confirm) {
                        typeid = Integer.parseInt(id);
                        infoItemAdapter.setSelection(confirm);
                        infoItemAdapter.notifyDataSetChanged();
                        itemDialog.setConfirmed(confirm);
                        itemsList.clear();
                        clearViewPager();
                        infoBannerTitle.setText("");
                        infoAdapter.notifyDataSetChanged();
//                        if (infoItem.get(position).getTitle().equals("老方点评")) {
//                            presenter.oldFangList(1);
//                            presenter.oldFangBanner();
//                            isOldFang = true;
//                        } else {
                        presenter.getFlag(id);
                        presenter.getIhome(id, "1", "9");
                        isOldFang = false;
//                        }

                        page = 1;
                        ctype = confirm;
                        isLastPage = false;
                        infoRefresh.setRefreshing(true);
                        isLoad = true;
                    }
                }
            }
        });

        dialog = new LoadingDialog(getActivity());
        dialog.show();
        infoContent.setVisibility(View.GONE);

        dotList = new ArrayList<>();
        unselect = new LinearLayout.LayoutParams(DeviceUtil.dip2px(getActivity(), 5), DeviceUtil.dip2px(getActivity(), 5));
        unselect.leftMargin = DeviceUtil.dip2px(getContext(), 6);
        unselect.gravity = Gravity.BOTTOM;

        selectParams = new LinearLayout.LayoutParams(DeviceUtil.dip2px(getActivity(), 7), DeviceUtil.dip2px(getActivity(), 7));
        selectParams.leftMargin = DeviceUtil.dip2px(getContext(), 6);
        selectParams.gravity = Gravity.BOTTOM;

        initClickBtn();
        initToolBar();
        initInfoItem();
        initList();
        initViewPager();

        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(getActivity());
        userid = dataEntity.getUserid();

        return view;
    }


    @Override
    public void onStart() {
        super.onStart();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        infoBanner.stopTurning();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initClickBtn() {
        infoBtnMsg.setOnClickListener(this);
        imageviewDialog.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.info_btn_msg: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(getContext());
                if (dataEntity.getUserid() == null || dataEntity.getUserid().isEmpty()) {
                    intent = new Intent(getActivity(), LoginAcivity.class);
                    intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.INFO_TO_LOGIN);
                } else {
                    intent = new Intent(getActivity(), MyCommentActivity.class);
                }
                startActivity(intent);
                break;
            }
            case R.id.imageview_dialog:
                itemDialog.show();
        }
    }

    private void initToolBar() {
        toolbar.setTitle("荟萃");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));

        //显示drawerlayout
//        toolbar.setNavigationIcon(R.mipmap.main_drawer);
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DrawerLayout drawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
//                drawerLayout.openDrawer(Gravity.LEFT);
//            }
//        });

        toolbar.setNavigationIcon(R.mipmap.product_company_search);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), InfoSearchActivity.class);
                intent.putExtra(Constant.SEARCH_INFO_TYPE, typeid);
                startActivity(intent);
            }
        });
    }

    private void initInfoItem() {
        ctypeIdList = new ArrayList<>();
        infoItem = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);

        infoItemAdapter = new InfoItemAdapter(infoItem);
        infoItemAdapter.setOnItemClickListener(new InfoItemAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, String id) {

                if (!infoRefresh.isRefreshing()) {
                    if (ctype != position) {
                        typeid = Integer.parseInt(id);
                        infoItemAdapter.setSelection(position);
                        infoItemAdapter.notifyDataSetChanged();
                        itemDialog.setConfirmed(position);
                        itemsList.clear();
                        clearViewPager();
                        infoBannerTitle.setText("");
                        infoAdapter.notifyDataSetChanged();
//                        if (infoItem.get(position).getTitle().equals("老方点评")) {
//                            presenter.oldFangList(1);
//                            presenter.oldFangBanner();
//                            isOldFang = true;
//                        } else {
                        presenter.getFlag(id);
                        presenter.getIhome(id, "1", "9");
                        isOldFang = false;
//                        }

                        page = 1;
                        ctype = position;
                        isLastPage = false;
                        infoRefresh.setRefreshing(true);
                        isLoad = true;
                    }
                }
            }
        });

        recycleview.setAdapter(infoItemAdapter);
        recycleview.setLayoutManager(manager);

        presenter = new UserPresenterImp();
        presenter.getCtype();
    }

    private void clearViewPager() {
        dot.removeAllViews();
        bannerUri.clear();
        infoBanner.notifyDataSetChanged();
    }

    private void initViewPager() {

        infoBanner.setPages(new CBViewHolderCreator<BannerAdapter>() {
            @Override
            public BannerAdapter createHolder() {
                return new BannerAdapter();
            }
        }, bannerUri);
        infoBanner.startTurning(3000);

        infoBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                infoBannerTitle.setText(bannerTitle.get(position));
                DeviceUtil.Log("position = " + position);
                initSelectDot(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        infoBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getContext(), InfoDetailActivity.class);
                intent.putExtra(Constant.INFO_DETAIL, bannerIdList.get(position));
                startActivity(intent);
            }
        });
    }

    private void initDots(List<String> bannerUrl) {

        dotList.clear();
        if (dot.getChildCount() != 0) {
            dot.removeAllViews();
        }

        for (int i = 0; i < bannerUrl.size(); i++) {
            dots = new ImageView(getActivity());
            if (i == 0) {
                dots.setLayoutParams(selectParams);
                dots.setBackgroundResource(R.drawable.bg_dots_select);
            } else {
                dots.setLayoutParams(unselect);
                dots.setBackgroundResource(R.drawable.bg_dots);
            }

            dot.addView(dots);
            dotList.add(dots);
        }
    }

    private void initList() {
        bannerTitle = new ArrayList<>();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_info_banner, null);
        infoBanner = (ConvenientBanner) view.findViewById(R.id.info_banner);
        infoBannerTitle = (TextView) view.findViewById(R.id.info_banner_title);
        dot = (LinearLayout) view.findViewById(R.id.dot);

        itemsList = new ArrayList<>();
        infoAdapter = new ProfessionInfoAdapter(getActivity(), itemsList);

        infoList.addHeaderView(view);
        infoList.setAdapter(infoAdapter);
        infoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), InfoDetailActivity.class);
                hasShown = false;
                if (!isOldFang) {
                    intent.putExtra(Constant.INFO_DETAIL, itemsList.get(position - 1).getId());
                } else {
                    intent.putExtra(Constant.OLD_FANG_DETAIL, itemsList.get(position - 1).getId());
                }
                startActivity(intent);
            }
        });

        helper = new SwipeRefreshHelper(infoRefresh, infoList, new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onRefresh() {

                if (!isLoad) {
                    page = 1;
                    isLastPage = false;
                    hasShown = false;
                    itemsList.clear();
                    bannerTitle.clear();
                    bannerUri.clear();
                    infoBanner.notifyDataSetChanged();
                    infoAdapter.notifyDataSetChanged();
                    if (isOldFang) {
                        presenter.oldFangBanner();
                        presenter.oldFangList(page);
                    } else {
                        presenter.getFlag(ctypeIdList.get(ctype));
                        presenter.getIhome(ctypeIdList.get(ctype), String.valueOf(page), null);
                    }
                }
            }

            @Override
            public void onLoad() {
                if (!isLastPage) {
                    page++;
                    if (!isOldFang) {
                        presenter.getIhome(infoType, String.valueOf(page), null);
                    } else {
                        presenter.oldFangList(page);
                    }
                } else {
                    if (!hasShown) {
                        DeviceUtil.MyToast(getActivity(), "已经是最后一页");
                        hasShown = true;
                    }
                }
            }
        });
    }

    public void onEventMainThread(OldFangBean bean) {
        if (infoRefresh.isRefreshing()) {
            infoRefresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            for (OldFangBean.DataBean d : bean.getData()) {
                GetIhomeBean.DataEntity dataEntity = new GetIhomeBean.DataEntity();
                dataEntity.setTimeline(d.getTimeline());
                dataEntity.setContent(d.getContent());
                dataEntity.setId(d.getId());
                dataEntity.setImg(d.getImg());
                dataEntity.setYs(d.getYs());
                itemsList.add(dataEntity);
            }
            infoAdapter.notifyDataSetChanged();
            isLoad = false;
        } else if (bean.getReturn_code() == -203) {
            isLastPage = true;
            DeviceUtil.MyToast(getContext(), "已经是最后一页");
        }
    }

    public void onEventMainThread(OldFangBannerBean bean) {
        bannerUri.clear();
        bannerTitle.clear();
        infoBanner.notifyDataSetChanged();
        if (bean.getReturn_code() == 0) {
            for (OldFangBannerBean.DataBean getFlag : bean.getData()) {
                bannerUri.add(getFlag.getImg_url());
                bannerTitle.add(getFlag.getTitle());
            }
            initDots(bannerUri);
            infoBanner.notifyDataSetChanged();
        }
    }

    /**
     * 咨询分类
     */
    public void onEventMainThread(GetCtypeBean bean) {
        if (bean.getReturn_code() == 0) {
            infoItem.addAll(bean.getData());
            infoItemAdapter.notifyDataSetChanged();
            infoType = bean.getData().get(0).getId();
            presenter.getIhome(bean.getData().get(0).getId(), String.valueOf(page), null);
            presenter.getFlag(bean.getData().get(0).getId());
            for (GetCtypeBean.DataEntity dataEntity : bean.getData()) {
                ctypeIdList.add(dataEntity.getId());

                ItemBean bean1 = new ItemBean();
                bean1.setId(dataEntity.getId());
                bean1.setTitle(dataEntity.getTitle());
                itemBeanList.add(bean1);
            }

            infoItemAdapter.setSelection(0);
            infoItemAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 图片轮播
     */
    public void onEventMainThread(GetFlagBean bean) {
        if (bean.getReturn_code() == 0) {
            List<GetFlagBean.DataEntity> list = bean.getData();
            bannerUri.clear();
            if (bean.getData() != null && !bean.getData().isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    bannerUri.add(bean.getData().get(i).getImg_url());
                    bannerTitle.add(bean.getData().get(i).getTitle());
                    bannerIdList.add(bean.getData().get(i).getId());
                }
            }
            initDots(bannerUri);
            infoBanner.notifyDataSetChanged();
        } else if (bean.getReturn_code() == -203) {
            DeviceUtil.MyToast(getActivity(), bean.getMsg());
        }
    }

    /**
     * 咨询列表
     */
    public void onEventMainThread(GetIhomeBean bean) {
        if (isLoad) {
            isLoad = !isLoad;
        }

        if (infoRefresh.isRefreshing()) {
            infoRefresh.setRefreshing(false);
        }

        if (bean.getReturn_code() == 0) {
            itemsList.addAll(bean.getData());
            itemsList.get((itemsList.size() - 1)).getYs();
            infoAdapter.notifyDataSetChanged();

            infoContent.setVisibility(View.VISIBLE);
        } else if (bean.getReturn_code() == -202) {
            DeviceUtil.MyToast(getActivity(), "已经是最后一页");
            isLastPage = true;
        } else {
            DeviceUtil.MyToast(getActivity(), "内容为空");
        }
        isListLoading = false;
        dialog.dismiss();
    }

    public void onEventMainThread(ErrorBean bean) {
        DeviceUtil.MyToast(getActivity(), bean.getErrorMsg());
        if (infoRefresh.isRefreshing()) {
            infoRefresh.setRefreshing(false);
        }
    }

    @Override
    public void showLoading() {
        dialog.show();
    }

    @Override
    public void hideLoading() {
        dialog.dismiss();
    }
}